
import imp
import os

from django.apps import apps
from django.conf import settings
from django.http import JsonResponse
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet

from mars.apps.orders.services import OrderService
from mars.apps.scheduler.models import AUTOBACKUP_JOB_ID, SchedulerJob

from .models import FuncPrice, MiniAppConfig
from .serializers import FuncPriceSerializer, MiniAppConfigSerializer
from .services import backup_dispatch

# from simpleui.templates.admin

VERSION_CODE = apps.get_app_config("oauth").__dict__["version_code"]
VERSION = apps.get_app_config("oauth").__dict__["version"]
DESCRIPTION = apps.get_app_config("oauth").__dict__["description"] or ""


def dashboard(request):
    context = OrderService.get_analysis_data()
    context["version"] = VERSION
    context["description"] = DESCRIPTION
    return render(request, "admin/task/dashboard.html", context)

# 数据库备份与恢复
def dbmanager(request):
    if request.method == 'GET':
        # 如果是GET请求，则返回操作页面
        # 获取当前数据库备份任务状态，返回给页面
        auto_backup_job = SchedulerJob.objects.filter(job_id=AUTOBACKUP_JOB_ID).first()
        context = {"status":0,"begin_time":"01:00"}
        if auto_backup_job:
            context ={
                "status":auto_backup_job.status,
                "begin_time":auto_backup_job.begin_time.strftime('%H:%M'),
                #"path":os.path.join(os.path.dirname(settings.BASE_DIR), "db_bak").replace('\\','/')
                "path":"jeekphoto/db_bak/"
            } 
        return render(request,"admin/dbmanager/dbmanager.html",context=context)
    elif request.method == 'POST':
        # 如果是POST请求，则根据传入的参数，执行备份动作
        result = backup_dispatch(request.POST)
        return JsonResponse(result)

class FuncPriceView(ReadOnlyModelViewSet):
    """功能价格视图"""

    queryset = FuncPrice.objects.all()
    serializer_class = FuncPriceSerializer

    def list(self, request, *args, **kwargs):
        # version = apps.get_app_config("oauth").__dict__["version"]
        qs = self.get_queryset()
        make_idphoto = qs[0].make_idphoto
        change_bg = qs[0].change_bg
        clip_photo = qs[0].clip_photo
        compress_photo = qs[0].compress_photo
        human_style = qs[0].human_style
        if VERSION_CODE == 0:
            make_idphoto = 0.01
            change_bg = 0.01
            clip_photo = 0.01
            compress_photo = 0.01
            human_style = 0.01
        elif VERSION_CODE == 1:
            human_style = 0.01
        objs = [
             FuncPrice(
                make_idphoto=make_idphoto,
                change_bg=change_bg,
                clip_photo=clip_photo,
                compress_photo=compress_photo,
                human_style=human_style,
            ),
        ]
        serializer = self.get_serializer(objs, many=True)
        return Response(serializer.data)

    def retrieve(self, request, *args, **kwargs):
        return super().list(request, *args, **kwargs)


class MiniAppConfigView(ReadOnlyModelViewSet):
    """小程序前端设置视图"""

    queryset = MiniAppConfig.objects.all()
    serializer_class = MiniAppConfigSerializer

